// Copyright (C) 2025, ZWSOFT Co., LTD.(Guangzhou)
// Licensed under the MIT License. See LICENSE in the project root for license information.

using CommunityToolkit.Mvvm.ComponentModel;
using CommunityToolkit.Mvvm.Input;
using System.Collections.ObjectModel;
using TestClient.Domain;

namespace TestClient.ViewModel;

public partial class SelectionFilter : ObservableObject
{
    public SelectionFilter(string name)
    {
        Name = name;
    }

    [ObservableProperty]
    public string name;

    [ObservableProperty]
    public bool isSelected;
}

public partial class SelectionTestViewModel : PageViewModelBase
{

    [ObservableProperty]
    private string entId = "";

    [ObservableProperty]
    private bool multiSelect = false;

    #region coord select
    [ObservableProperty]
    private string surfaceId = "";
    [ObservableProperty]
    private int numPts = 1;
    [ObservableProperty]
    private string coordList = "";
    #endregion

    #region Commands
    public IAsyncRelayCommand RunSelectCommand { get; }
    public IAsyncRelayCommand SelectSurfaceCommand { get; }
    public IAsyncRelayCommand SelectCoordsCommand { get; }
    #endregion

    public SelectionTestViewModel(
        VFAdapterWrapper wrapper,
        ISnackNotifyService notifyService) : base(wrapper, notifyService)
    {
        RunSelectCommand = CreateAsyncRpcCommand(RunSelect);
        SelectSurfaceCommand = CreateAsyncRpcCommand(SelectSurfaceAsync);
        SelectCoordsCommand = CreateAsyncRpcCommand(SelectCoordsAsync);
    }

    public ObservableCollection<SelectionFilter> Filters { get; } = [
            new("Point"),
            new("Curve"),
            new("Surface")
            ];

    private async Task RunSelect()
    {
        var selected = Filters.Where(x => x.IsSelected).Select(x => x.Name).ToList();
        var filterString = string.Join(", ", selected);
        EnsureConnected();

        if (MultiSelect)
        {
            var IDs = await Task.Run(() =>
            {
                return Wrapper.MultiSelect(filterString);
            });

            EntId = string.Join(", ", IDs);
        }
        else
        {
            EntId = await ViewModelHelpers.SelectEnt(Wrapper, filterString);
        }
    }

    private async Task SelectSurfaceAsync()
    {
        EnsureConnected();
        SurfaceId = await ViewModelHelpers.SelectEnt(Wrapper, "Surface");
    }

    private async Task SelectCoordsAsync()
    {
        EnsureConnected();
        var coords = await Task.Run(() =>
        {
            return Wrapper.PickPointCoord(SurfaceId, NumPts);
        });

        CoordList = string.Join(", ", coords.Select(c => c.ToString()));
    }
}
